package com.example.userprovider.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author likaiping
 * @createTime 2024/7/3 14:07
 */
@Component
public class GatewayFilter implements Filter {
    private String GATEWAY_TOKEN = "gateway-token";
    private String GATEWAY_TOKEN_VALUE = "this-is-gateway-request";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String gatewayToken = request.getHeader(GATEWAY_TOKEN);
        if (GATEWAY_TOKEN_VALUE.equals(gatewayToken)) {
            filterChain.doFilter(request,response);
        }else {
            // 401 状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized");
            System.out.println("请求方式不合法，只允许经过网关访问");
        }
    }
}
